var express = require("express");
var router = express.Router();
// 导入浮点运算decimal.js
let Dec = require("decimal.js");
const commodity = require("../model/commodity");
const exchange = require("../model/exchange");
const user_login = require("../model/user_login");
const completeTask = require("../model/completeTask");
const mutex = require('process-key-mutex');
router.post("/api/v1/exchangeGoods", async function(req, res) {
  let goodID = req.body.goodID;
  let userID = req.body.userID;
  var exchangeTpye = req.body.exchangeTpye;
  var receiving_address = req.body.receiving_address;
  await mutex.lock(goodID, async() => {
    var goods = await commodity.findById({ _id: goodID }).exec();
    var users = await user_login.findById({ _id: userID }).exec();
  //判断库存
  if (parseFloat(goods.stock) >= 1) {
    console.log(goods, users);
    var goodsintegral = goods.integral;
    var usersintegral = users.integral;
    //判断用户积分是否足够兑换商品
    if (parseFloat(goodsintegral) > parseFloat(usersintegral)) {
      res.json({
        code: 200,
        text: "积分不足兑换该物品"
      });
    } else {
      //修改商品库存数量减少1
      commodity.findByIdAndUpdate(
        { _id: goodID },
        {
          $inc: { stock: -1 }
        },
        function(err) {
          if (err) {
            res.json({
              code: 200,
              text: err
            });
            return;
          }
          //计算兑换后 用户剩余多少积分
          var lastInt = Dec(usersintegral)
            .sub(new Dec(goodsintegral))
            .toNumber();
          //修改用户积分
          user_login.findByIdAndUpdate(
            { _id: userID },
            {
              $set: {
                integral: lastInt
              }
            },
            async function(err) {
              if (err) {
                res.json({
                  code: 200,
                  text: err
                });
                return;
              }

              //生成积分变动表
              var completeTaskdata = {
                userid: userID, //用户id
                inttype: "reduce", //积分变动类型
                complete_time: new Date(), //完成时间
                integral: goodsintegral, //变动积分
                taskPoints: goodsintegral, //任务原有积分};
                goodid: goodID //商品id
              };
              completeTask.create(completeTaskdata);

              var exchangedata = {
                userid: userID, //用户id
                commodityid: goodID, //商品id
                exchangeTpye: exchangeTpye, //兑换方式  //邮寄  自提
                order_time: new Date(), //订单时间
                receiving_address: receiving_address, //收货地址
                exchange_num: "EX" + Date.parse(new Date())
              };

              var exchangeS = await exchange.create(exchangedata);
              res.json({
                code: 200,
                text: "兑换成功",
                exchangeId: exchangeS._id
              });
            }
          );
        }
      );
    }
  } else {
    res.json({
      code: 200,
      text: "该物品库存不足"
    });
  }
});
});
module.exports = router;
